//导入用户首选项模块。
import preferences from '@ohos.data.preferences';
//初始化对象
class  PreferencesUtil{
  preMap:Map<string,preferences.Preferences>=new Map()
  async loadPreference(context,name:string){
    try {
      let pref = await  preferences.getPreferences(context,name)
      this.preMap.set(name,pref)
      console.log(`加载preference${name}成功`)
    }catch(e){
      console.log(`加载preference${name}失败`,JSON.stringify(e))
    }
  }

  //存储
  async putPreferenceVale(name:string,key:string,value:preferences.ValueType){
    if(!this.preMap.has(name)){
      console.log(`加载preference${name}失败`,`${name},尚未初始化`)
      return
    }
    try{
      console.log(JSON.stringify(value),'你好')
      let pref=this.preMap.get(name)
      // @ts-ignore
      await pref.put(key,JSON.stringify(value))
      // @ts-ignore
      await  pref.flush()

      console.log("成功",`保存${name}.${key}=${value}成功`)
      // return value
    }catch(e){
      console.log("保存失败",JSON.stringify(e))
    }
  }

  //读
  async getPreferenceValue(name:string,key:string,defaultVale:preferences.ValueType){
    if(!this.preMap.has(name)){
      console.log(`加载preference${name}失败`,`${name},尚未初始化`)
      return
    }
    try{
      console.log(JSON.stringify(this.preMap),'hhhh')
      let pref=this.preMap.get(name)
      // @ts-ignore
      console.log(JSON.stringify(pref),"赛666666")
      let value=  await pref.get(key,defaultVale)
      console.log("testTag",`读取${name},${key}=${value}成功}`)
      return value
    }catch(e){
      console.log("读取失败",JSON.stringify(e))
    }
  }

  //删除
  async deletePreferenceValue(name: string, key: string) {
    if (!this.preMap.has(name)) {
      console.log(`加载preference${name}失败`, `${name},尚未初始化`)
      return
    }
    try {
      let pref = this.preMap.get(name);
      // 使用 delete 方法删除指定键对应的数据
      await pref.delete(key);
      await  pref.flush()
      console.log("testTag", `删除${name},${key}成功`);
    } catch (e) {
      console.log("删除失败", JSON.stringify(e));
    }
  }



  pref(pref: any,arg1: string) {
    throw new Error('Method not implemented.');
  }

}
const preferencesUtil = new PreferencesUtil();

export default preferencesUtil as PreferencesUtil;
